package com.guaoran.distributed.netty.chat.server.handler;

import com.guaoran.distributed.netty.chat.processor.MessageProcessor;
import com.guaoran.distributed.netty.chat.protocol.IMMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.log4j.Logger;

/**
 * @Author gucheng
 * @Description socket 处理类
 * 2019-04-19 17:27
 */
// TODO 为什么要继承这个类
public class SocketHandler extends SimpleChannelInboundHandler<IMMessage> {
    private Logger logger = Logger.getLogger(this.getClass());
    private MessageProcessor processor = new MessageProcessor();

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, IMMessage imMessage) throws Exception {
        processor.sendMessage(channelHandlerContext.channel(),imMessage);
    }
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        logger.info("服务端Handler创建...");
        super.handlerAdded(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // (3)
        Channel client = ctx.channel();
        processor.logout(client);
        logger.info("Socket Client:" + processor.getNickName(client) + "离开");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("channelInactive");
        super.channelInactive(ctx);
    }
    /**
     * tcp链路建立成功后调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("Socket Client: 有客户端连接："+ processor.getAddress(ctx.channel()));
    }


    /**
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.info("Socket Client: 与客户端断开连接:"+cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }
}
